/*
 * Copyright (C) 2012 Johan Boris Iantila jiantila@gmail.com && http://www.facebook.com/johanboris.iantila
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package mg.daloji.antandroyd.ui;


import java.util.ArrayList;
import java.util.HashMap;


import mg.daloji.antandroyd.CONSTANTS;
import mg.daloji.antandroyd.R;
import mg.daloji.antandroyd.Radio;
import mg.daloji.antandroyd.application.App;
import mg.daloji.antandroyd.service.IServiceRadio;
import mg.daloji.antandroyd.service.IServiceRadioCallBack;
import mg.daloji.antandroyd.service.ServiceRadio;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.DialogInterface.OnCancelListener;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


/**
 *
 * 
 * @author Johan Boris Iantila
 *
 */


public class Home extends Activity{

	private static final int TEXT_UPDATE = 0;
	private static String PACKAGE ="com.speakingcode.example.android.MediaPlayerService";
	private ImageButton btnPlay;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageView image;
	private ImageButton btnBack;
	private SeekBar songProgressBar;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	// Media Player
	private  MediaPlayer mMediaPlayer;
	
	private ServiceRadio service;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();;

	private Context mContext;

	private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
	
	
	private IServiceRadioCallBack mObserver;
	private ServiceConnection mConnection;
	private Radio radio_select;
	private boolean mBound =false; 
	private boolean isplaying =false;
	private ProgressDialog mWaitDialog;
	private IServiceRadio mService;
	private int current_radio=0;
	private long timeInMilliseconds = 0L;
	private long timeSwapBuff = 0L;
	private long updatedTime = 0L;
	private long startTime = 0L;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player);
		Bundle extras = getIntent().getExtras(); 
		if (extras != null) {
			current_radio = extras.getInt(CONSTANTS.INDEX);
		}
		mContext=getApplicationContext();
		mWaitDialog = new ProgressDialog(this);
		songTitleLabel=(TextView) findViewById(R.id.songTitle);
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
		btnBack =(ImageButton) findViewById(R.id.btnPlaylist);
		songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
		songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
		image =(ImageView) findViewById(R.id.image);
		// set Progress bar values
		songProgressBar.setProgress(0);
		songProgressBar.setMax(100);
		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(mBound){
					if(isplaying){
						try {
							mService.doStop(mObserver);
							mService.removeObserver(mObserver);
							unbindService(mConnection);
							finish();
						} catch (RemoteException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}	
					}
				}
				
				
			}
		});
		
		btnPlay.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// check for already playing
				if(mBound){
					try{
						if(!isplaying){
							playRadio();
						}else{
							isplaying=false;
					    	btnPlay.setImageResource(R.drawable.btn_play);
					    	mHandler.removeCallbacks(mUpdateTimeTask);
					    	mService.doStop(mObserver);
						}
					}catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		
		
		btnNext.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
		       try {
		    	   current_radio++;
				   if(current_radio>App.getConf().size()-1){
						current_radio=0;
					}
				   mHandler.removeCallbacks(mUpdateTimeTask);
			       radio_select =App.getConf().get(current_radio);
			       songTitleLabel.setText(radio_select.getNom()); 
			       //image.setImageBitmap(radio_select.getImage());
			       setImage(radio_select.getTrigramme());
			       showWaitDialog();
			       mService.doStop(mObserver);
				   mService.doStart(mObserver, radio_select);
		       } catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
			
		});
		
		btnPrevious.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
			    	   current_radio--;
			    	   if(current_radio<0){
			    		  current_radio=App.getConf().size() -1;
			    	   }
			    	   mHandler.removeCallbacks(mUpdateTimeTask);
				       radio_select =App.getConf().get(current_radio);
				       songTitleLabel.setText(radio_select.getNom()); 
				       //image.setImageBitmap(radio_select.getImage());
				       setImage(radio_select.getTrigramme());
				       showWaitDialog();
				       mService.doStop(mObserver);
					   mService.doStart(mObserver, radio_select);
			       } catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});
		mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what){
				case TEXT_UPDATE:
					songTitleLabel.setText((CharSequence) msg.obj);
				}
			}
		};
		
		 mObserver = new IServiceRadioCallBack.Stub() {

			@Override
			public void streamingReady() throws RemoteException {
				// TODO Auto-generated method stub
				hideWaitDialog();
				startTime = SystemClock.uptimeMillis();
				mHandler.postDelayed(mUpdateTimeTask, 100);
			}

			@Override
			public void errorStreaming() throws RemoteException {
				// TODO Auto-generated method stub
				hideWaitDialog();
				Toast.makeText(mContext, "Erreur de synchronisation "
	    			      + Thread.currentThread().getName(), Toast.LENGTH_LONG).show();
			}

			@Override
			public void stopallStreaming() throws RemoteException {
				// TODO Auto-generated method stub
				isplaying=false;
		    	btnPlay.setImageResource(R.drawable.btn_play);
		    	mHandler.removeCallbacks(mUpdateTimeTask);
		    	mService.doStop(mObserver);
			}
			
		
		};
		
		mConnection = new ServiceConnection(){	
    		public void onServiceDisconnected(ComponentName name) {
    			mService = null;
    
    		}


			@Override
			public void onServiceConnected(ComponentName arg0, IBinder service) {
				// TODO Auto-generated method stub
				mService = IServiceRadio.Stub.asInterface(service);
    			try{
    				mService.setObserver(mObserver);
    			}catch(RemoteException e){
    			}
    			mBound = true;
    			playRadio();
			}
    	};
		
    	bindService();
	}

	
	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
			   timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
			   updatedTime = timeSwapBuff + timeInMilliseconds;
			   int secs = (int) (updatedTime / 1000);
			   int mins = secs / 60;
			   secs = secs % 60;
			   int milliseconds = (int) (updatedTime % 1000);
			   

			   // Displaying Total Duration time
			   songTotalDurationLabel.setText("" + mins + ":"
					   + String.format("%02d", secs)) ;
			   // Displaying time completed playing
			   songCurrentDurationLabel.setText("00:00");
			   
			   songProgressBar.setProgress(100);
			   
			   // Running this thread after 100 milliseconds
		       mHandler.postDelayed(this, 100);
		   }
		};
		
  private void playRadio(){
	  radio_select=App.getConf().get(current_radio);
	  if(radio_select!=null){
		  try {
			    isplaying=true;
				radio_select=App.getConf().get(current_radio);
				songTitleLabel.setText(radio_select.getNom());
				//image.setImageBitmap(radio_select.getImage());
			    //image.setImageResource(R.drawable.antsiva);
				setImage(radio_select.getTrigramme());
				btnPlay.setImageResource(R.drawable.btn_pause);
			    showWaitDialog();
			    mService.doStart(mObserver, radio_select);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	  }
  }
	
	
  private void setImage(String name){
	  
	  if(name.equalsIgnoreCase(CONSTANTS.ANTSIVA)){
		  image.setImageResource(R.drawable.antsiva); 
	  }
	  if(name.equalsIgnoreCase(CONSTANTS.RDJ)){
		  image.setImageResource(R.drawable.rdj); 
	  }
	  if(name.equalsIgnoreCase(CONSTANTS.VIVA)){
		  image.setImageResource(R.drawable.viva); 
	  }
	  if(name.equalsIgnoreCase(CONSTANTS.RNM)){
		  image.setImageResource(R.drawable.rnm); 
	  }
	  if(name.equalsIgnoreCase(CONSTANTS.RDB)){
		  image.setImageResource(R.drawable.rdb); 
	  }
	  if(name.equalsIgnoreCase(CONSTANTS.ALLIANCE)){
		  image.setImageResource(R.drawable.alliance1); 
	  }
	  if(name.equalsIgnoreCase(CONSTANTS.TARATRA)){
		  image.setImageResource(R.drawable.taratra); 
	  }
	  if(name.equalsIgnoreCase(CONSTANTS.RVM)){
		  image.setImageResource(R.drawable.rvm); 
	  }
		 
  }
  
	/**
	 * Dismisses the wait dialog if any
	 */
	private void hideWaitDialog() {
		if(mWaitDialog!=null && mWaitDialog.isShowing()){
			this.mWaitDialog.dismiss();
		}
	}
	
	private void showWaitDialog() {
		// just in case:
		hideWaitDialog();
		try {
			this.mWaitDialog.setOwnerActivity(this);
			mWaitDialog = ProgressDialog.show(this,radio_select.getNom(),"Synchronisation",true,true,new OnCancelListener() {
				public void onCancel(final DialogInterface dialog) {
					finish();
				}
			});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void bindService(){
		Intent intent = new Intent(getApplicationContext(), ServiceRadio.class);
		bindService(intent, mConnection, BIND_AUTO_CREATE);
	}

	private boolean haveNetworkConnection() {
	    boolean haveConnectedWifi = false;
	    boolean haveConnectedMobile = false;

	    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
	    for (NetworkInfo ni : netInfo) {
	        if (ni.getTypeName().equalsIgnoreCase(CONSTANTS.WIFI))
	            if (ni.isConnected())
	                haveConnectedWifi = true;
	        if (ni.getTypeName().equalsIgnoreCase(CONSTANTS.MOBILE))
	            if (ni.isConnected())
	                haveConnectedMobile = true;
	    }
	    return haveConnectedWifi || haveConnectedMobile;
	}
	/**
	 * Receiving song index from playlist view
	 * and play the song
	 * */
	@Override
	protected void onActivityResult(int requestCode,
			int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}


	@Override
	public void onDestroy(){
		super.onDestroy();
		if (mWaitDialog!=null) {
            if (mWaitDialog.isShowing()) {
            	mWaitDialog.dismiss();       
            }
        }
		mService=null;
		mObserver=null;
		mConnection=null;
	}
	
	public final boolean isInternetOn(){
		boolean state=false;
		ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
				connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ){
			state= true;
		}
		else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
				||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED  )
		{
			state=false;
		}
		return state;
	}
	
	private BroadcastReceiver mconnectionState = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			if(!isInternetOn()){
				showError();
			}
		}
	};
	
	
	
	 void showError() {
	        final AlertDialog.Builder builder =  new AlertDialog.Builder(this)
	            .setTitle(R.string.app_name) 
	            .setMessage(R.string.service_error_network)
	            .setIcon(android.R.drawable.ic_dialog_alert)
	            .setCancelable(false);
	        
	        builder.setPositiveButton(R.string.service_positive_error_network,new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	            	//On affiche dans un Toast le texte contenu dans l'EditText de notre AlertDialog
	            	Toast.makeText(getApplicationContext(),R.string.service_error_network, Toast.LENGTH_SHORT).show();
	          } }); 
	        
	  }


}